package com.marktotop.validation;

import com.marktotop.utils.ValidatorUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * IsMobileValidator 手机号码校验规则
 *
 * @author WXLD
 * @Data 2021/6/18
 * @Since 1.0
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean required = false;

    /**
     * 初始化
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        if (required){
            return ValidatorUtil.isMobile(str);
        } else {
            if (StringUtils.isEmpty(str)){
                return true;
            } else {
                return ValidatorUtil.isMobile(str);
            }
        }
    }
}
